import gtk

class Rect(object):
    def __init__(self, xywh):
        """
        xywh must be a 2 or 4 tuple or a rect instance.
        """
        if isinstance(xywh, Rect):
            self.left = xywh.left
            self.top = xywh.top
            self.width = xywh.width
            self.height = xywh.height
        else:
            if len(xywh) == 4:
                self.left, self.top, self.width, self.height = (i for i in xywh)
            elif len(xywh) == 2:
                self.left, self.top, self.width, self.height = (0.0,0.0) + tuple(i for i in xywh)

    def __repr__(self):
      return "<Rect (%d, %d) %d x %d>" % (
      self.left, self.top, self.width, self.height)

    def set_right(self, s):
        self.left = s - self.width

    def get_right(self):
        return self.left + self.width

    right = property(get_right, set_right)

    def set_bottom(self, s):
        self.top = s - self.height

    def get_bottom(self):
        return self.top + self.height

    bottom = property(get_bottom, set_bottom)

    def collidepoint(self, xy):
        """
        Test if a point intersects with this rect.
        """
        x,y = xy
        return (x >= self.left and
            x <= (self.left + self.width) and
            y >= self.top and
            y <= (self.top + self.height))

    def intersects(self, other):
        """
        Test if a rect intersects with this rect.
        """
        if self.left > other.left+other.width: return False
        if self.top > other.top + other.height: return False
        if self.left + self.width < other.left: return False
        if self.top + self.height < other.top: return False
        return True

    def GetGdkRectangle(self):
      return gtk.gdk.Rectangle(self.left, self.top, self.width, self.height)


